const ollamaUrl = "http://192.168.1.10:11434/";
//const ollamaUrl = "http://tx8.maoshan:11434/";
function formatText(text) {
    // 基本的文本整理逻辑
    text = text.replace(/\d+\./g, ''); // 删除数字和后面的点
    text = text.replace(/\*\*/g, ''); 
    let result = '';
    let inQuotes = false;
    let quoteHasPunctuation = false; // 新增标记：引号内是否有标点
    for (let i = 0; i < text.length; i++) {
        const char = text[i];
        result += char;
        if (char === '“') {
            inQuotes = true;
            quoteHasPunctuation = false; // 遇到左引号时重置标记
        } else if (char === '”') {
            inQuotes = false;
            // 仅当引号内有标点 且 下一个字符不是换行符时换行
            if (quoteHasPunctuation && i + 1 < text.length && text[i + 1] !== '\n') {
                result += "\n";
            }
        }
        // 在引号内时检测标点
        if (inQuotes && (char === '。' || char === '？' || char === '！')) {
            quoteHasPunctuation = true;
        }
        // 如果遇到句号、问号、感叹号，且不在双引号内，则换行
        if (!inQuotes && (char === '。' || char === '？' || char === '！')) {
            result += "\n";
          
        }
    }
    text = result.trim(); // 去除首尾空格  
    //删除连续的换行符
    text = text.replace(/\n{2,}/g, '\n');

    return text;
}
/**
 * 向Ollama发送流式请求
 * @param {string} model - 模型名称
 * @param {string} prompt - 提示词
 * @param {function} onData - 接收数据的回调函数
 * @param {object} options - 可选参数
 * @param {number} options.temperature - 温度参数
 * @param {number} options.maxTokens - 最大token数
 * @returns {Promise} 返回Promise对象
 */



async function streamOllamaRequest(question, prompt, onData, model = "gemma3:27b-it-qat", count = 3000) {
    const controller = new AbortController();
    
    try {
        question += "\n请用纯文本回答，不要用markdown格式。";
        const response = await fetch(`${ollamaUrl}api/chat`, {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            signal: controller.signal,
            body: JSON.stringify({
                model,
                stream: true,
                options: {
                    temperature: 1.0,
                    num_predict:count,
                    max_tokens: count,
                    top_p: 1.0,
                    top_k: 50,
                    repeat_penalty: 1.0,
                    presence_penalty: 1.0,
                    frequency_penalty: 1.0,
                },
                messages:[
                    {
                        role: "system",
                        content: prompt,
                    },
                    {
                        role: "user",
                        content: question, 
                    }
                ]
            })
        });

        if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);

        const reader = response.body.getReader();
        const decoder = new TextDecoder();
        
        while (true) {
            const {done, value} = await reader.read();
            if (done) break;

            decoder.decode(value).split('\n')
                .filter(line => line.trim())
                .forEach(line => {
                    try {
                        const {message} = JSON.parse(line);
                        if (message) {
                            const shouldContinue = onData(message.content, () => controller.abort());
                            if (shouldContinue === false) controller.abort();
                        }
                    } catch (e) {
                        console.error('解析JSON失败:', e);
                    }
                });
        }
    } catch (error) {
        if (error.name !== 'AbortError') {
            console.error('请求Ollama失败:', error);
            throw error;
        }
    }
}



export default {
    streamOllamaRequest,
    formatText
};
// 导出函数
// export { streamOllamaRequest, prompt, formatText};